package org.msfj.authority.server.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import org.msfj.authority.client.config.JwtConfig;
import org.msfj.authority.server.service.UserAuthService;
import org.msfj.authority.server.util.JwtAuthenticationRequest;
import org.msfj.common.base.BaseController;
import org.msfj.common.model.CommonResult;
import org.msfj.common.util.AesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static org.msfj.common.annotation.Constants.USER_PERMS_KEY_PREFIX;

@RestController
@RequestMapping("userJwt")
public class UserAuthController extends BaseController {
    @Autowired
    JwtConfig jwtConfig;

    @Autowired
    private UserAuthService userAuthService;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    /**
     * 根据用户名和密码验证登录
     *
     * @param jwtAuthenticationRequest
     * @return
     * @throws Exception
     */
    @RequestMapping("token")
    public CommonResult createAuthenticationToken(JwtAuthenticationRequest jwtAuthenticationRequest) throws Exception {
        if (validateVerifyCode(redisTemplate, jwtAuthenticationRequest.getVerifyCode(), jwtAuthenticationRequest.getRandom(), true)) {
            final String token = userAuthService.login(AesUtil.aesDecrypt(jwtAuthenticationRequest.getAccount()), AesUtil.aesDecrypt(jwtAuthenticationRequest.getPassword()));
            if (StrUtil.isBlank(token)) {
                return CommonResult.build(200,"用户名或密码错误",false);
            }
            //重新登录之后清空权限缓存
            this.redisTemplate.delete(USER_PERMS_KEY_PREFIX + jwtAuthenticationRequest.getAccount());
            return CommonResult.ok(token);
        } else {
            return CommonResult.build(200,"验证码不正确",false);
        }

    }

    @RequestMapping("refresh")
    public CommonResult refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(jwtConfig.getUserTokenHeader());
        String refreshedToken = userAuthService.refresh(token);
        if (refreshedToken == null) {
            return CommonResult.error("");
        } else {
            return CommonResult.ok(refreshedToken);
        }
    }

    /**
     * 作废登录
     *
     * @param request
     * @return
     */
    @RequestMapping("invalid")
    public CommonResult invalid(HttpServletRequest request) throws Exception {
        String token = request.getHeader(jwtConfig.getUserTokenHeader());
        userAuthService.invalid(token);
        return CommonResult.ok(true);
    }
}
